package websocket

import (
	"github.com/gorilla/websocket"
	"net/http"
)

const (
	// TextMessage denotes a text data message. The text message payload is
	// interpreted as UTF-8 encoded text data.
	TextMessage = websocket.TextMessage

	// BinaryMessage denotes a binary data message.
	BinaryMessage = websocket.BinaryMessage

	// CloseMessage denotes a close control message. The optional message
	// payload contains a numeric code and text. Use the FormatCloseMessage
	// function to format a close message payload.
	CloseMessage = websocket.CloseMessage

	// PingMessage denotes a ping control message. The optional message payload
	// is UTF-8 encoded text.
	PingMessage = websocket.PingMessage

	// PongMessage denotes a pong control message. The optional message payload
	// is UTF-8 encoded text.
	PongMessage = websocket.PongMessage
)

type Client struct {
	*websocket.Conn
}

// Write 实现io.Writer接口
func (this *Client) Write(p []byte) (int, error) {
	err := this.Conn.WriteMessage(websocket.TextMessage, p)
	return len(p), err
}

// ReadMessage 实现io.MessageReader接口(自定义)
func (this *Client) ReadMessage() ([]byte, error) {
	_, bytes, err := this.Conn.ReadMessage()
	return bytes, err
}

// Close 实现io.Closer接口
func (this *Client) Close() error {
	return this.Conn.Close()
}

// New 新建websocket连接
// 基于github.com/gorilla/websocket
// 进行了简单的封装,用于实现IO接口
func New(url string, header http.Header) (*Client, error) {
	c, _, err := websocket.DefaultDialer.Dial(url, header)
	return &Client{Conn: c}, err
}
